package lm.spring.feign.support;

import feign.Client;
import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import feign.slf4j.Slf4jLogger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * feign client factory
 * @author liangming 2021-12-25 0:03
 */
public class FeignFactoryBean implements FactoryBean<Object>, ApplicationContextAware {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(FeignFactoryBean.class);

    /**
     * 日志级别配置的属性名
     * <ol>
     * <li>NONE:不记录任何日志</li>
     * <li>BASIC:仅记录请求方法，url,响应状态码以及执行时间</li>
     * <li>HEADERS:basic基础上，记录请求和响应的header</li>
     * <li>FULL:basic基础上，记录请求和响应的header,body,元数据</li>
     * <ol/>
     */
    private static final String FEIGN_LOG_LEVEL_NAME = "feign.logLevel";
    private static final String FEIGN_LOG_DEFAULT = "BASIC";///默认日志级别

    private boolean singleton = true;
    private Object instance = null;

    private Class<?> objectType;
    private ApplicationContext applicationContext;

    @Override
    public Object getObject() throws Exception {
        if (singleton && instance != null) {
            return instance;
        }

        return createFeignClientBean(objectType);
    }

    private Object createFeignClientBean(Class<?> aFeignClass) {
        FeignClient feignClient = aFeignClass.getAnnotation(FeignClient.class);

        String url = resolveUrl(feignClient);
        Client client = resolveClient(feignClient);
        Decoder decoder = resolveDecoder(feignClient);
        Encoder encoder = resolveEncoder(feignClient);
        ErrorDecoder errorDecoder = resolveErrorDecoder(feignClient);
        Logger.Level logLevel = resolveLogLevel(feignClient);

        synchronized (FeignFactoryBean.class) {
            if (instance == null) {
                instance = Feign.builder()
                        .logger(new Slf4jLogger())
                        .logLevel(logLevel)
                        .client(client)
                        .decoder(decoder)
                        .encoder(encoder)
                        .errorDecoder(errorDecoder)
                        .options(new Request.Options(feignClient.connectTimeout(), TimeUnit.MILLISECONDS, feignClient.readTimeout(), TimeUnit.MILLISECONDS, true))
                        .target(aFeignClass, url);
            }
        }

        return instance;
    }

    private Client resolveClient(FeignClient feignClient) {
        String client = feignClient.client();
        log.debug("创建feign对象, client={}", client);
        return (Client) applicationContext.getBean(client);
    }

    /**
     * 日志级别(默认使用全局配置feign.logLevel,全局配置默认为BASIC)
     * <ol>
     * <li>NONE:不记录任何日志</li>
     * <li>BASIC:仅记录请求方法，url,响应状态码以及执行时间</li>
     * <li>HEADERS:basic基础上，记录请求和响应的header</li>
     * <li>FULL:basic基础上，记录请求和响应的header,body,元数据</li>
     * <ol/>
     */
    private Logger.Level resolveLogLevel(FeignClient feignClient) {
        String logLevel = feignClient.logLevel();
        if (!StringUtils.hasText(logLevel)) {
            logLevel = getProperty(FEIGN_LOG_LEVEL_NAME, FEIGN_LOG_DEFAULT);
        }

        log.debug("创建feign对象, logLevel={}", logLevel);
        return Logger.Level.valueOf(logLevel);
    }

    private ErrorDecoder resolveErrorDecoder(FeignClient feignClient) {
        String errorDecoder = feignClient.errorDecoder();
        log.debug("创建feign对象, errorDecoder={}", errorDecoder);
        return (ErrorDecoder) applicationContext.getBean(errorDecoder);
    }

    private Encoder resolveEncoder(FeignClient feignClient) {
        String encoder = feignClient.encoder();
        log.debug("创建feign对象, encoder={}", encoder);
        return (Encoder) applicationContext.getBean(encoder);
    }

    private Decoder resolveDecoder(FeignClient feignClient) {
        String decoder = feignClient.decoder();
        log.debug("创建feign对象, decoder={}", decoder);
        return (Decoder) applicationContext.getBean(decoder);
    }

    private String resolveUrl(FeignClient feignClient) {
        String serviceName = feignClient.serviceName();
        String url = getProperty(serviceName, serviceName);
        url = StringUtils.trimTrailingCharacter(url, '/');

        String path = feignClient.path();
        if (StringUtils.hasText(path)) {
            url = url + StringUtils.replace(("/" + path), "//", "/");
        }

        log.debug("创建feign对象, url={}", url);
        return url;
    }

    /**
     * 获取属性值，默认返回null
     * @param key 属性
     * @return
     */
    private String getProperty(String key) {
        return getProperty(key, null);
    }

    /**
     * 获取属性值，默认返回<code>defaultValue</code>
     * @param key 属性
     * @param defaultValue 默认值
     * @return
     */
    private String getProperty(String key, String defaultValue) {
        String result = null;

        Collection<AbstractEnvironment> environments = applicationContext.getBeansOfType(AbstractEnvironment.class).values();
        Collection<Properties> beansProps = applicationContext.getBeansOfType(Properties.class).values();
        for (AbstractEnvironment environment : environments) {
            result = environment.getProperty(key);
            if (StringUtils.hasText(result)) {
                break;
            }
        }

        if (!StringUtils.hasText(result)) {
            for (Properties prop : beansProps) {
                result = prop.getProperty(key);
                if (StringUtils.hasText(result)) {
                    break;
                }
            }
        }

        if (StringUtils.hasText(result)) {
            return result;
        }

        return defaultValue;

    }

    @Override
    public Class<?> getObjectType() {
        return objectType;
    }

    public void setObjectType(Class<?> objectType) {
        this.objectType = objectType;
    }

    @Override
    public boolean isSingleton() {
        return singleton;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
